package io.renren.modules.piclocalupload.service.impl;

import io.renren.common.exception.RenException;
import io.renren.common.utils.DateUtils;
import io.renren.modules.piclocalupload.service.PicLocalUploadService;
import io.renren.modules.piclocalupload.vo.PictureInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
public class PicLocalUploadServiceImpl implements PicLocalUploadService {

    /**
     * 上传图片和图稿资源路径
     */
    @Value("${upload.path}")
    private String path;

    /**
     * 上传图片和图稿资源路径
     */
    @Value("${upload.uploads}")
    private String uploadsPath;

    @Value("${fileUrl}")
    private String fileUrl;

    private static final String IMAGE_SUFFIX = "jpg,png,pneg,jpeg";

    @Override
    public PictureInfoVO uploadPic(MultipartFile uploadFile) {
        log.info("本地图片上传");
        if(Objects.isNull(uploadFile)) {
            //判断文件是否为空
            throw new RenException("Please upload the picture again");
        }
        // 获取源文件名
        String oldFileName = uploadFile.getOriginalFilename();
        // 获取后缀名
        String prefix = FilenameUtils.getExtension(oldFileName);
        // 判断文件名是否合法
        if (!IMAGE_SUFFIX.contains(prefix)) {
            throw new RenException("Upload file format error");
        }
        // 对文件重新命名
        String uuid = UUID.randomUUID().toString();
        String newFileName = uuid + "." + prefix;
        try {
            // 判断文件夹是否存在，不存在则创建
            String filePath = DateUtils.format(new Date(), "yyyyMMdd");
            File targetFile = new File(this.path + this.uploadsPath + File.separator + filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            // 将文件写到服务器指定的文件
            String pathName = this.path + this.uploadsPath + File.separator + filePath + File.separator
                    + newFileName;
            File dest = new File(pathName);
            uploadFile.transferTo(dest);
            // 将图片名称和地址传出
            PictureInfoVO pictureInfoVo = new PictureInfoVO();
            pictureInfoVo.setImgName(filePath + "/" + newFileName);
            pictureInfoVo.setImgAddress(this.fileUrl + this.uploadsPath + "/" + filePath + "/" + newFileName);
            return pictureInfoVo;
        } catch (IOException e) {
            throw new RenException("Upload error");
        }
    }
}
